package io.externalize;

import java.io.Externalizable;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.Scanner;

import day4.p2.EmptyValueException;

public class Student implements Externalizable {

	private int rollNo, age;
	private String name, address;

	public Student() {
	}

	public void create() {
		try {
			Scanner sc = new Scanner(System.in);

			System.out.print("Enter Roll Number: ");
			int rollNo = sc.nextInt();
			if (rollNo <= 0)
				throw new EmptyValueException("Invalid Roll Number");

			System.out.print("Enter Name:");
			String name = sc.next();
			if (name.length() == 0)
				throw new EmptyValueException("Name Field is left blank");

			System.out.print("Enter Age:");
			int age = sc.nextInt();
			if (age <= 0) throw new EmptyValueException("Invalid Age");

			System.out.print("Enter Address:");
			String address = sc.next();
			if (address.length() == 0)
				throw new EmptyValueException("Address Field is left blank");

			this.address = address;
			this.age = age;
			this.name = name;
			this.rollNo = rollNo;
		} catch (NullPointerException e) {
			System.out.println(e.toString());
			create();
		} catch (NumberFormatException e) {
			System.out.println(e.toString());
			create();
		} catch (EmptyValueException e) {
			System.out.println(e.toString());
			create();
		} catch (Exception e) {
			System.out.println(e.toString());
			create();
		}
	}

	public String toString() {
		return this.rollNo + "\t" + this.name + "\t" + this.age + "\t"
				+ this.address;
	}

	public void writeExternal(ObjectOutput out) throws IOException {
		out.writeInt(this.rollNo);
		out.writeUTF(this.name);
		out.writeInt(this.age);
		out.writeUTF(this.address);
	}

	public void readExternal(ObjectInput in) throws IOException,
			ClassNotFoundException {
		this.rollNo = in.readInt();
		this.name = in.readUTF();
		this.age = in.readInt();
		this.address = in.readUTF();
	}
}
